package Java8实战._1_Lambda._8_使用Lambda并将List类型抽象;

import Java8实战._1_Lambda.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _8_使用Lambda并将List类型抽象 {

    public static void main(String[] args) {
        List<Apple> inventory = Arrays.asList(
                new Apple("red",150),
                new Apple("green",123),
                new Apple("green",189)
        );

        List<Apple> result;

        result = filter(inventory, (Apple apple) -> "green".equals(apple.getColor()));
        print(result, (Apple apple) ->"苹果的颜色：" + apple.getColor() + "，苹果的重量：" + apple.getWeight());

        System.out.println("\n================================\n");

        List<Integer> numList = Arrays.asList(
                1,2,3,4
        );
        List<Integer> numResult;

        numResult = filter(numList, (Integer i) -> i % 2 == 0);
        print(numResult, (Integer i) -> "偶数：" + i);
    }

    public static <T> List<T> filter(List<T> inventory, Predicate<T> predicate){
        List<T> list = new ArrayList<>();

        for (T t : inventory){
            if(predicate.test(t)){
                list.add(t);
            }
        }
        return list;
    }

    public static <T> void print(List<T> list, Formatter<T> formatter){

        for (T t : list){
            System.out.println(formatter.accept(t));
        }
    }
}
